import axios from 'axios';
import { Message } from 'element-ui';

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_SERVER_API, // api的base_url
  withCredentials: true,
  timeout: 15000 // 请求超时时间
});
service.defaults.withCredentials = true;
// request拦截器
service.interceptors.request.use(config => {
  return config;
}, error => {
  Promise.reject(error);
});

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错
     */
    const res = response.data;
    if (res.code !== 200) {
      Message({
        message: res.data.msg,
        type: 'error',
        duration: 3 * 1000
      });
    } else {
      return response.data;
    }
  },
  error => {
    if (error.response.data.error['error-code'] === '420') {
      Message({
        message: '号码不能重新购买',
        type: 'error',
        duration: 3 * 1000
      });
    } else {
      Message({
        message: error.response.data.msg,
        type: 'error',
        duration: 3 * 1000
      });
    }
    return Promise.reject(error);
  }
);

export default service;
